package com.lanou3g.springcloud.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenFilter extends ZuulFilter {
	@Override
	public String filterType() {
		return "pre"; //定义filter的类型，有pre、route、post、error四种
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String token = request.getParameter("token");
		ctx.getRequestQueryParams();
		boolean isValid = false;
			if(StringUtils.isNotBlank(token)) {
				isValid = true;

			} else {
				isValid = false;
			}
		if(isValid) {
			ctx.setSendZuulResponse(true);
			ctx.setResponseStatusCode(200);
		} else {
			ctx.setSendZuulResponse(false);
			HttpServletResponse response = ctx.getResponse();
			response.setStatus(403);
			response.setContentType("text/html;charset=UTF-8");
			try {
				response.getWriter().print("<script>alert('非法用户，再胡闹我要报警了!');</script>");
				ctx.setResponse(response);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
